package opentelemetry

import (
	web "gitee.com/youkelike/web"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/trace"
)

const instrumentationname = "gitee.com/youkelike/web/middleware/opentelemetry"

type MiddlewareBuilder struct {
	Tracer trace.Tracer
}

func NewMiddlerwareBuild(tracer trace.Tracer) *MiddlewareBuilder {
	return &MiddlewareBuilder{
		Tracer: tracer,
	}
}

func (m MiddlewareBuilder) Build() web.Middleware {
	if m.Tracer == nil {
		m.Tracer = otel.GetTracerProvider().Tracer(instrumentationname)
	}

	return func(next web.HandlerFunc) web.HandlerFunc {
		return func(ctx *web.Context) {
			reqCtx := ctx.Req.Context()
			// 把其它进程的 trace 结合
			reqCtx = otel.GetTextMapPropagator().Extract(reqCtx, propagation.HeaderCarrier(ctx.Req.Header))
			_, span := m.Tracer.Start(reqCtx, "unknown")
			defer span.End()

			span.SetAttributes(attribute.String("http.method", ctx.Req.Method))
			span.SetAttributes(attribute.String("http.url", ctx.Req.URL.String()))

			next(ctx)

			span.SetName(ctx.MathedRoute)
		}
	}
}
